package com.store.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.R;
import com.store.app.adapter.GroupListAdapter;
import com.store.app.bean.GroupBean;
import com.store.app.hyphenate.Constant;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/1.\
 * 我创建的群
 */
public class MyGroupActivity extends BaseActivity implements IOnHttpListener {
    private static final String TAG = "MyGroupActivity";
    private ImageView public_ll_return;
    private TextView tvTitle;
    private ListView group_listview;
    private GroupListAdapter groupListAdapter;
    private List<GroupBean> groupBeanList;
    private NetRequest netRequest;

    //requesId,用于区分不同的网络请求
    private final static int QUERY_GROUP_LIST = 1;
    private final static int DISSOLVE_GROUP = 2;

    private static int delete_group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_my_group);
        initView();
        initData();
    }

    private void initData() {
        groupBeanList = new ArrayList<>();
        groupListAdapter = new GroupListAdapter(this, groupBeanList);
        group_listview.setAdapter(groupListAdapter);
        netRequest = new NetRequest(this);
        if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
            netRequest.requestHXGroupList(QUERY_GROUP_LIST, LocationApplication.im_user_id);
            showProgressDialog("", "正在加载我的群组...");
        }
    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        group_listview = (ListView) findViewById(R.id.group_listview);
        tvTitle.setText("我的群组");

        //item的点击事件，点击进入群聊天页面
        group_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String groupId = groupBeanList.get(position).getId();
                if (TextUtils.isEmpty(groupId)) {
                    ToastTools.showShort(MyGroupActivity.this, "该群已解散！");
                } else {
                    Intent intent = new Intent(MyGroupActivity.this, ChatActivity.class);
                    intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                    intent.putExtra("userId", groupId);
                    startActivity(intent);
                }
            }
        });


        //item的长按事件，解散群聊
        group_listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                delete_group = i;

                final String groupId = groupBeanList.get(i).getId();
                String groupName = groupBeanList.get(i).getName();
                if (TextUtils.isEmpty(groupId)) {
                    ToastTools.showShort(MyGroupActivity.this, "该群已解散");

                } else {
                    //弹出dialog；通知后台删除此群，更新list数据
                    AlertDialog.Builder deletGroup = new AlertDialog.Builder(MyGroupActivity.this);
                    deletGroup.setCancelable(false);
                    deletGroup.setMessage("解散“" + groupName + "”群?");

                    deletGroup.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    });

                    deletGroup.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //通知后台，删除群
                            if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                                netRequest.requestHXDissolveGroup(DISSOLVE_GROUP, groupId, LocationApplication.im_user_id);
                            }
                        }
                    });

                    deletGroup.show();

                }

                return true;
            }
        });

    }


    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        showToast("请检查本地网络!");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();

        switch (requestId) {
            case QUERY_GROUP_LIST:
                try {
                    Gson gson = new Gson();
                    JSONArray jsonArray = new JSONArray(result);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        GroupBean groupBean = gson.fromJson(jsonObject.toString(), GroupBean.class);
                        groupBeanList.add(groupBean);
                    }
                    Log.v("zyl", "groupBeanList.size:" + groupBeanList.size());
                    groupListAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
//              requestURL：https://t-appportal.meitianhui.com/openapi/community?service=chat.deleteChatGroup&sign=60e5be08cb48cf4e1bf863fea96b71e7&user_token=ed69af1fe56c47a9be5704b55ffbc9a6f800ad416872f33d5f4c21d820087b58cbfa0ce04ebbf4a18e82e96b65e16dd9&params={"group_id":"264312992303153588","im_user_id":"e642dc34361b4c43b2c407d181595ccc"}

                break;

            case DISSOLVE_GROUP:
                //删除list数据，更新UI
                groupBeanList.remove(delete_group);
                groupListAdapter.notifyDataSetChanged();

                break;

            default:
                break;

        }

//        if (requestId == 1) {
//            try {
//                Gson gson = new Gson();
//                JSONArray jsonArray = new JSONArray(result);
//                for (int i = 0; i < jsonArray.length(); i++) {
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    GroupBean groupBean = gson.fromJson(jsonObject.toString(), GroupBean.class);
//                    groupBeanList.add(groupBean);
//                }
//                groupListAdapter.notifyDataSetChanged();
//            } catch (Exception e) {
//            }
//        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        ToastTools.showShort(this, msg);
    }
}
